package com.zhugang.week13.stack;

import java.util.Stack;

/**
 * @program algorithms
 * @description: RemoveDuplicateStr
 * @author: chanzhugang
 * @create: 2022/11/01 20:08
 */
public class RemoveDuplicateStr {

    /**
     * 删除连续重复字符(腾讯实习)
     * 3个重复的字符会删除
     *
     * @param str
     * @return
     */
    public String remove(String str) {
        // 栈实现：栈中存储的是没有消掉的字符，画个图模拟下
        // 遍历字符，如果栈为null，压入栈；如果字符和栈顶元素不想等，压入；相等，比较数量是否为3个
        Stack<CharWithCount> stack = new Stack<>();
        int n = str.length();
        for (int i = 0; i < n; i++) {
            char c = str.charAt(i);
            if (stack.isEmpty()) {
                // 栈为null， 压入栈
                stack.push(new CharWithCount(c, 1));
                continue;
            }

            CharWithCount peek = stack.peek();
            if (c != peek.c) {
                // 字符不相等，压入栈
                stack.push(new CharWithCount(c, 1));
                continue;
            }
            if (peek.count == 2) {
                // 字符相等，个数满足3个，弹出字符(消除)
                stack.pop();
                continue;
            }
            // 字符相等，个数不满足3个，++
            peek.count++;
        }
        // 把栈中数据取出来拼成字符串
        StringBuilder sb = new StringBuilder();
        while (!stack.isEmpty()) {
            CharWithCount pop = stack.pop();
            for (int i = 0; i < pop.count; i++) {
                sb.append(pop.c);
            }
        }
        return sb.reverse().toString();
    }

    class CharWithCount {
        public char c;
        public int count;

        public CharWithCount(char c, int count) {
            this.c = c;
            this.count = count;
        }
    }

    public static void main(String[] args) {
        RemoveDuplicateStr removeDuplicateStr = new RemoveDuplicateStr();
        String result = removeDuplicateStr.remove("abbaaabcc");
        System.out.println(result);
    }
}